package org.jimmy.mqtt.controller;

/**
 * @author create by jimmy 2116398125@qq.com
 * @package org.jimmy.mqtt.controller
 * @date 2024/8/14 20:39
 */
import org.jimmy.mqtt.client.EmqMqttClient;
import org.jimmy.mqtt.enums.QoSEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import jakarta.annotation.Resource;
import java.net.URLDecoder;

/**
 * 消息订阅控制器
 * @date 2024/8/16 10:04
 * @author create by jimmy 2116398125@qq.com
 */
@Controller
public class SubController {
    @Resource
    private EmqMqttClient client;

    @Value("${spring.mqtt.client-id}")
    private String clientId;

    @RequestMapping("/sub/connect")
    @ResponseBody
    public String connect() {
        client.connect();
        return clientId + "连接到服务器";
    }

    @GetMapping("/sub/subscribe")
    @ResponseBody
    public String subscribe(@RequestParam("topic") String topic, @RequestParam("qos") QoSEnum qos) {
        topic = URLDecoder.decode(topic);
        System.out.println("topic:" + topic);
        client.subscribe(topic, qos);
        return clientId + "已订阅Topic:" + topic + " QoS: " + qos.getCode();
    }

    @GetMapping("/sub/unSubscribe")
    @ResponseBody
    public String unSubscribe(@RequestParam("topic") String topic) {
        client.unSubscribe(topic);
        return clientId + "已取消订阅Topic:" + topic;
    }

    @RequestMapping("/disConnect")
    @ResponseBody
    public String disConnect() {
        client.disConnect();
        return clientId + "与服务器断开连接";
    }
}